package com.cs.framework.web.context;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.util.Log4jWebConfigurer;

import com.cs.framework.core.context.Application;
import com.cs.framework.web.util.WebConstant;

/**
 * Servelet上下文监听
 * 
 * @author hedongzhou
 * 
 */
public class WebContextListener implements ServletContextListener {

	protected Log logger = LogFactory.getLog(getClass());

	/**
	 * 应用上下文类型
	 */
	protected String applicationClass;

	public WebContextListener() {
		applicationClass = "com.cs.framework.web.context.WebApplication";
	}

	public void contextInitialized(ServletContextEvent event) {
		ServletContext context = event.getServletContext();

		Log4jWebConfigurer.initLogging(context);

		logger.info("CS start...");

		// 创建应用上下文
		Application app = WebContextHelper.createApplication(context, applicationClass);

		context.setAttribute(WebConstant.APPLICATION_CONTEXT_ATTR, app);
	}

	public void contextDestroyed(ServletContextEvent event) {
		logger.info("CS stop...");

		ServletContext context = event.getServletContext();
		context.setAttribute(WebConstant.APPLICATION_CONTEXT_ATTR, null);
	}

}
